﻿using SqlSugar;
using Fortunate.IService;
using Fortunate.Service.BASE;
using Fortunate.Application.Entities;
using Fortunate.ViewModel;
using Fortunate.ViewModel.FilesModule;

namespace Fortunate.Service
{
    public class FilesTableService : BaseServices<FilesTable>, IFilesTableService
    {
        public FilesTableService(ISqlSugarClient _db) : base(_db)
        {
        }

        /// <summary>
        /// 获取文件数据
        /// </summary>
        /// <param name="search"></param>
        /// <returns></returns>
        public async Task<DataModel<FilesTable>> GetFilesListAsync(FilesSearch search)
        {
            DataModel<FilesTable> dataModel = new DataModel<FilesTable>();
            RefAsync<int> total = 0;
            dataModel.Data = await db.Queryable<FilesTable>()
            .Where(x => x.IsValid == false)
            .WhereIF(!string.IsNullOrEmpty(search.ID), x => x.id.ToString() == search.ID)
            .ToPageListAsync(search.PageIndex, search.PageCount, total);
            dataModel.Total = total.Value;
            return dataModel;
        }

        /// <summary>
        /// 添加数据
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        public async Task<bool> InsertFilesTableAsync(FilesTable entity)
        {
            return await db.Insertable(entity).ExecuteCommandAsync() > 0;
        }

        /// <summary>
        /// 获取单个对象
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<FilesTable> GetFilesTableObjectAsync(Guid id)
        {
            return await db.Queryable<FilesTable>().FirstAsync(x => x.id == id);
        }

        /// <summary>
        /// 删除文件(假删除)
        /// </summary>
        /// <param name="id">文件id</param>
        /// <returns></returns>
        public async Task<bool> DeleteFilesTableAsync(Guid id)
        {
            var entity = await db.Queryable<FilesTable>().Where(x => x.id == id).FirstAsync();
            entity.IsValid = true;
            return await db.Updateable(entity).UpdateColumns(x => x.IsValid).WhereColumns(x => x.id).ExecuteCommandAsync() > 0;
        }

        /// <summary>
        /// 删除文件数据
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<bool> DropFilesTableAsync(Guid id)
        {
            //return await db.Deleteable<FilesTable>().In(it => it.id, id).ExecuteCommandAsync() > 0;
            return await db.Deleteable<FilesTable>().Where(x => x.id == id).ExecuteCommandAsync() > 0;
        }
    }
}
